package com.xd.cloud.common.Interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xd.cloud.common.annotation.DataAuthValidate;
import com.xd.cloud.common.bean.MessageBean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author wangtao
 * @class_name DataAuthorityInterceptor
 * @description 数据权限拦截器
 * @create 2017/12/27
 */
public class DataAuthorityInterceptor  extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            DataAuthValidate methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(DataAuthValidate.class);
            if(methodAnnotation != null){
                printMessage(response,new MessageBean(false,"权限不足"));
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }

    public static void printMessage(HttpServletResponse response, Object res) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(toJson(res));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null){
                writer.close();
            }
        }
    }
    public static String toJson(Object object)  {
            return JSON.toJSONString(object, new SerializerFeature[] {
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.DisableCircularReferenceDetect,
                    SerializerFeature.WriteNonStringKeyAsString });
    }
}
